/* typehints:start */
import { Application } from "../application";
/* typehints:end */

import { MUSIC, SOUNDS } from "./sound/interface";
import { createLogger } from "./utils/logging";

const logger = createLogger('resource_loader')

export class ResourceLoader{
  constructor(app){
    /** @type {Application} */
    this.app = app;
  }

  startLoading(){
    let promises = [];

    for(let key in SOUNDS){
      promises.push(
        this.app.sound.loadSound(SOUNDS[key])
        .catch(err => {
          logger.warn('SOUND加载错误: ', SOUNDS[key]);
        })
      )
    }

    for(let key in MUSIC){
      promises.push(
        this.app.sound.loadSound(MUSIC[key])
        .catch(err => {
          logger.warn('MUSIC加载错误: ', MUSIC[key]);
        })
      )
    }

    for(let i = 0; i < G_ALL_UI_IMAGES.length; i++){
      const imgUrl = G_ALL_UI_IMAGES[i]
      promises.push(
        Promise.race([
          new Promise((resolve, reject) => {
            setTimeout(reject.bind(this, '加载时间过长，请查看你的网络是否正常'), G_IS_DEV ? 5000 : 25000)
          }),
          new Promise(resolve => {
            let img = new Image;
            let triesSofar = 0;

            img.onload = () => {
              img.onerror = null;
              img.onload = null;

              if(typeof img.decode === 'function'){
                img.decode().then(
                  () => null,
                  () => null
                )
              }

              resolve();
            }

            img.onerror = reason => {
              logger.warn('加载错误: ', imgUrl, reason);
              if(++triesSofar < 4){
                logger.log('加载图片', url, '正在重试');
                img.src = 'res/' + imgUrl + '?try=' + triesSofar;
              } else {
                logger.warn('加载失败', url, '已经重试加载', triesSofar + '(次)', reason);
                img.onerror = null;
                img.onload = null;
                resolve();
              }
            }

            img.src = 'res/' + imgUrl;
          })
        ])
      )
    }

    return Promise.all(promises)
  }
}